package parser

import (
	"fmt"

	"vitess.io/vitess/go/vt/sqlparser"
)

func convertDelete(d *sqlparser.Delete, query string) (Statement, error) {
	if len(d.TableExprs) > 1 {
		return nil, fmt.Errorf("unsupported syntax: cannot delete from multiple tables")
	}

	table := d.TableExprs[0].(*sqlparser.AliasedTableExpr)
	tableName := table.Expr.(sqlparser.TableName)
	stmt := &DeleteStatement{
		Columns: ColumnSet{},
		db:      tableName.Qualifier.String(),
		tbl:     tableName.Name.String(),
	}
	stmt.sql = query

	err := SQLNodeToColumns(stmt.Columns, d)
	if err != nil {
		return nil, err
	}

	where, err := whereToWhereExpr(d.Where)
	if err != nil {
		return nil, err
	}
	stmt.where = where
	return stmt, nil
}

type DeleteStatement struct {
	BaseStatement
	Columns ColumnSet
	db      string
	tbl     string
	where   *WhereExpr
}

func (s *DeleteStatement) Database() string {
	return s.db
}

func (s *DeleteStatement) Table() string {
	return s.tbl
}

func (s *DeleteStatement) Where() *WhereExpr {
	return s.where
}
